package com.moko.task;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import com.moko.R;
import com.moko.ShowActivity;
import com.moko.view.Dialog;

public class LoadShowTask extends AsyncTask<String, Integer, String> {
	// 可变长的输入参数，与AsyncTask.exucute()对应
	ProgressDialog pdialog;
	Context context;

	public LoadShowTask(Context context) {
		this.context = context;
		pdialog = new ProgressDialog(context);
		pdialog.setMessage(context.getText(R.string.loading));
		pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pdialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				LoadShowTask.this.cancel(true);
			}
		});
		pdialog.show();
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			HttpClient client = new DefaultHttpClient();
			// params[0]代表连接的url
			HttpGet get = new HttpGet(params[0]);
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			String s = null;
			if (is != null) {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[128];
				int ch = -1;
				while ((ch = is.read(buf)) != -1) {
					baos.write(buf, 0, ch);
				}
				s = new String(baos.toByteArray());
			}
			// 返回结果
			return s;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(String data) {
		// 返回JSON数据
		if (null == data || "".equals(data)) {
			pdialog.dismiss();
			Dialog.getInstance().checkNetworkDialog(context);
		} else {
			Intent intent = new Intent();
			intent.putExtra("data", data);
			intent.setClass(context, ShowActivity.class);
			context.startActivity(intent);
			pdialog.dismiss();
		}
	}

}
